package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.component.UMengPushComponent;
import com.lebang.domain.MemberHeaderHistory;
import com.lebang.entity.MemberVideoCheck;
import com.lebang.entity.PointwallRecord;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.TbTaskAotian;
import com.lebang.entity.task.TaskXianwan;
import com.lebang.example.MemberVideoCheckExample;
import com.lebang.example.PointwallRecordExample;
import com.lebang.mapper.*;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.buss.MemberTradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import static com.lebang.model.RedisKey.SYS_SETTING;
import static com.lebang.model.RedisKey.VIDEO;
import static com.lebang.service.TaskInRedisService.HASH_CSJ;

/**
 * @Author: hwq
 * @Date: 2019/5/31 18:05
 * @Version 1.0
 */
@Service
public class PointWallSdkService {
    @Autowired
    private UMengPushComponent uMengPushComponent;
    @Autowired
    private TaskXianwanMapper taskXianwanMapper;
    @Autowired
    private MemberTradeService memberTradeService;
    @Autowired
    private TbTaskAotianMapper tbTaskAotianMapper;
    @Autowired
    private PointwallRecordMapper pointwallRecordMapper;
    @Autowired
    private LbbMemberTradeMapper tradeMapper;
    @Autowired
    private PointService pointService;
    @Autowired
    private MemberNewTaskService memberNewTaskService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MemberNoticeService memberNoticeService;
    @Autowired
    private MemberVideoCheckMapper videoCheckMapper;
    @Autowired
    private MemberHeaderHistoryMapper memberHeaderHistoryMapper;
    private static final Logger log = LoggerFactory.getLogger(PointWallSdkService.class);

    public int insert(TaskXianwan taskXianwan) {
        return taskXianwanMapper.insertSelective(taskXianwan);
    }

    public int getByOrderNum(String ordernum) {
        return taskXianwanMapper.getByOrderNum(ordernum);
    }


    public boolean xianwan(TaskXianwan taskXianwan, String memberId, Integer userMoney) {
        try {
            RequestHeaders requestHeaders = getRequestHeaders(memberId);
            int t = this.insert(taskXianwan);
            int m = memberTradeService.addMoney(memberId, userMoney, "闲玩任务奖励:" + taskXianwan.getEvent(),
                    taskXianwan.getEvent(), taskXianwan.getOrderNum(), requestHeaders,
                    JSON.toJSONString(taskXianwan), new MoneyCategory(Whether.YES,TaskCategory.XianWan,taskXianwan.getPrice()));
            if (t > 0 && m > 0) {
                memberNoticeService.addNoticeAndPush("闲玩任务奖励", taskXianwan.getEvent(),memberId,requestHeaders);
                return true;
            } else {

                return false;
            }
        } catch (Exception e) {
            log.error("处理失败" + taskXianwan.getOrderNum(), e);

            return false;
        }


    }


    public boolean aotian(TbTaskAotian aotian, Integer money) {
        try {
            RequestHeaders requestHeaders = getRequestHeaders(aotian.getMemberId());
            aotian.setCreateTime(new Date());
            int t = tbTaskAotianMapper.insertSelective(aotian);
            int m = memberTradeService.addMoney(aotian.getMemberId(), money,
                    "傲天任务奖励:" + aotian.getDescription(),
                    aotian.getDescription(), aotian.getOrderId(),
                    requestHeaders, JSON.toJSONString(aotian),
                    new MoneyCategory(Whether.YES,TaskCategory.AoTian,aotian.getMoney().multiply(new BigDecimal(2))));
            if (t > 0  && m > 0) {
                memberNoticeService.addNoticeAndPush("傲天任务奖励", aotian.getDescription(),
                        aotian.getMemberId(),requestHeaders);
                return true;
            } else {

                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }

    }

    public boolean checkAotianOrder(String orderId) {
        int i = tbTaskAotianMapper.selectByOrderId(orderId);
        return i > 0;
    }

    public boolean getByOrderNum(String ordernum, TaskCategory pcdandan) {
        return pointwallRecordMapper.getByOrderNum(ordernum, pcdandan.name()) > 0;
    }

    /**
     * 加钱
     *
     * @param taskCategory
     * @param re
     * @param money
     * @return
     */

    public boolean creatOrder(TaskCategory taskCategory, PointwallRecord re, int money) {
        re.setType(0);
        try {
            RequestHeaders requestHeaders = getRequestHeaders(re.getMemberId());
            int t = pointwallRecordMapper.insertSelective(re);
            int m = memberTradeService.addMoney(re.getMemberId(), money, re.getEvent(),
                    re.getEvent(), re.getOrderNum(),
                    requestHeaders, JSON.toJSONString(re),  new MoneyCategory(Whether.YES,taskCategory,re.getMyMoney()));
            if (t > 0 && m > 0) {
                uMengPushComponent.sendNoRead(taskCategory.getTitle() + "通知", re.getEvent(), re.getMemberId());
                memberNewTaskService.pushRecord(taskCategory, re.getMemberId());
                return true;
            } else {

                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }

    }

    /**
     * 加金币
     *
     * @param taskCategory
     * @param re
     * @param money
     * @return
     */

    public boolean creatOrderByPoint(TaskCategory taskCategory, PointwallRecord re, int point) {
        re.setType(1);
        try {
            int t = pointwallRecordMapper.insertSelective(re);
            RequestHeaders requestHeaders = getRequestHeaders(re.getMemberId());
            boolean m = pointService.addPointBySdk(re.getMemberId(), point, taskCategory, re.getEvent(),requestHeaders);
            //memberTradeService.addMoney(re.getMemberId(), money, re.getEvent(), re.getEvent(), re.getOrderNum(), new RequestHeaders(), JSON.toJSONString(re));
            if (t > 0 && m) {
                uMengPushComponent.sendNoRead(taskCategory.getTitle() + "通知", re.getEvent(), re.getMemberId());
                memberNewTaskService.pushRecord(taskCategory, re.getMemberId());
                return true;
            } else {

                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }

    }

    public BigDecimal sumPointWallByTime(String appStore, LocalDateTime star, LocalDateTime end, int type) {
        return pointwallRecordMapper.sumPointWallByTime(appStore, star, end, type);
    }

    public BigDecimal sumXianwanByTime(String appStore, LocalDateTime star, LocalDateTime end, int type) {
        return taskXianwanMapper.sumXianwanByTime(appStore, star, end, type);
    }

    public BigDecimal sumAotianByTime(String appStore, LocalDateTime star, LocalDateTime end, int type) {
        return tbTaskAotianMapper.sumAotianByTime(appStore, star, end, type);
    }

    public int sumUserByTime(String appStore, LocalDateTime star, LocalDateTime end, int type) {
        return tradeMapper.sumUserByTime(appStore, star, end, type);
    }

    public int sumUserOutLay(String appStore, LocalDateTime star, LocalDateTime end, int type) {
        return tradeMapper.sumUserOutLay(appStore, star, end, type);
    }

    public long countByExample(PointwallRecordExample example) {
        return pointwallRecordMapper.countByExample(example);
    }

    public List<PointwallRecord> selectByExample(PointwallRecordExample example) {
        return pointwallRecordMapper.selectByExampleWithBLOBs(example);
    }




    public int getMoneyByVideoCheck(String memberId) {
        Integer count = 0;
        String obj = redisClient.hget(HASH_CSJ, memberId);
        if (obj != null) {
            count = Integer.parseInt(obj);
        }
        count=count+1;
        List<MemberVideoCheck> videoChecks =this.getList();
        for (Iterator<MemberVideoCheck> iterator = videoChecks.iterator(); iterator.hasNext(); ) {
            MemberVideoCheck next = iterator.next();
            if (count > next.getCount()) {
             //   return new BigDecimal(next.getMoney()).divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
                return next.getMoney()<50?50:next.getMoney();
            }
        }
        //return new BigDecimal(0.02);
        //默认200金币
        return 200;
    }

    public List<MemberVideoCheck> getList(){
        List<MemberVideoCheck> videoChecks ;
        String str = redisClient.hget(SYS_SETTING, VIDEO);
        if (str != null) {
            videoChecks = JSON.parseArray(str, MemberVideoCheck.class);
        } else {
            MemberVideoCheckExample example = new MemberVideoCheckExample();
            example.createCriteria().andHasDeletedEqualTo(0);
            example.setOrderByClause("count desc");
            videoChecks = videoCheckMapper.selectByExample(example);
            redisClient.hset(SYS_SETTING, VIDEO, JSON.toJSONString(videoChecks));
        }
        return videoChecks;
    }

    public RequestHeaders getRequestHeaders(String memberId){
        Optional<MemberHeaderHistory> memberHeaderHistory = Optional.ofNullable(memberHeaderHistoryMapper.selectOneByMemberId(memberId));
        return new RequestHeaders(memberHeaderHistory.orElse(new MemberHeaderHistory()));
    }

}
